package com.hk.kindheartedness;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.model.User;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.RegexUtil;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.Date;
import java.util.Objects;

/**
 * 处理患者个人信息展示且修改
 */
public class PatientPersonInfoActivity extends AppCompatActivity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //  Initialize button
    private Button updatePersonInfoBtn;

    private EditText userName,age,address;

    private TextView userId,phone,medicalCardNumber,idNumber;

    private RadioButton man,woman;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_person_info);
//        实例化
        dbOpenHelper = new DBOpenHelper(PatientPersonInfoActivity.this, "db_kindheartedness", null, 1);
//        获取个人信息控制权
        userId = findViewById(R.id.userId);
        userName = findViewById(R.id.userName);
        phone = findViewById(R.id.phone);
        medicalCardNumber = findViewById(R.id.medicalCardNumber);
        idNumber = findViewById(R.id.idNumber);
        age = findViewById(R.id.age);
        address = findViewById(R.id.address);
//         获取性别控制权
        man = findViewById(R.id.man);
        woman = findViewById(R.id.woman);
//        获取更新按钮控制权
        updatePersonInfoBtn = findViewById(R.id.updatePersonInfoBtn);
        updatePersonInfoBtn.setOnClickListener(this);

//        提取出当前用户传递的个人信息
        Intent intent2 = getIntent();
        Bundle bundle = intent2.getExtras();
//        回显获取的个人信息
        echoPersonInfo(bundle);


    }

    /**
     * 回显当前登录用户的个人信息
     * @param bundle
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void echoPersonInfo(Bundle bundle) {
        if (Objects.isNull(bundle)) {
            toast = ToastUtil.toastHint(toast,PatientPersonInfoActivity.this,"获取个人信息失败,请重试！");
            return;
        }
        String userToString = (String) bundle.get("user");
        if (Objects.nonNull(userToString)) {
            User user = JSON.parseObject(userToString, User.class);
//                进行回显
            userId.setText(user.getId().toString());
            userName.setText(user.getUserName());
            phone.setText(user.getPhone());
            medicalCardNumber.setText(user.getMedicalCardNumber());
            idNumber.setText(user.getIdNumber());
            age.setText(user.getAge().toString());
//                进行性别判断
            if (user.getSex() == 0) {
                man.setChecked(true);
            } else {
                woman.setChecked(true);
            }
            address.setText(user.getAddress());
            return;
        }
        toast = ToastUtil.toastHint(toast,PatientPersonInfoActivity.this,"获取个人信息失败,请重试！");
        return;

    }

    /**
     * 点击事件处理
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.updatePersonInfoBtn:
//                更新当前登录账户个人信息
                updatePersonInfo();
                break;
            default:
                return;
        }
    }

    /**
     * 更新当前账户个人信息
     */
    private void updatePersonInfo() {
        //                更新个人信息
        String patientId = userId.getText().toString();
        String patientUserName = userName.getText().toString();
        String patientAge = age.getText().toString();
//        判断选择的性别
        String patientSex = "0";
        if (woman.isChecked()) {
            patientSex = "1";
        }
        String patientAddress = address.getText().toString();
        Boolean check = checkPatientData(patientId,patientUserName,patientAge,patientSex,patientAddress);
        if (check) {
            SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//                    封装需要更新的采购员信息
            ContentValues contentValues = new ContentValues();
            contentValues.put("username",patientUserName);
            contentValues.put("age",patientAge);
            contentValues.put("sex",patientSex);
            contentValues.put("address",patientAddress);
            contentValues.put("update_time", DateUtil.dateString(new Date()));
//                    执行更新采购员信息
            int update = readableDatabase.update("user", contentValues, "id = ?", new String[]{patientId});
            if (update == 1) {
                toast = ToastUtil.toastHint(toast, PatientPersonInfoActivity.this, "个人信息更新成功，请返回进行查看！");
                return;
            }
            toast = ToastUtil.toastHint(toast, PatientPersonInfoActivity.this, "个人信息更新失败，请稍后重试！");
            return;
        }
    }

    /**
     * 校验个人信息
     *
     * @param patientId Id
     * @param patientUserName 姓名
     * @param patientAge 年龄
     * @param patientSex 性别
     * @param patientAddress 地址
     * @return
     */
    private Boolean checkPatientData(String patientId, String patientUserName, String patientAge, String patientSex,String patientAddress) {
        //        校验医生编号
        if (patientId.equals("") || patientId.equals(null) || patientId == null) {
            toast = ToastUtil.toastHint(toast,PatientPersonInfoActivity.this,"编号不能为空！");
            return false;
        }
        if (!RegexUtil.checkChinese(patientUserName)) {
            toast = ToastUtil.toastHint(toast,PatientPersonInfoActivity.this,"姓名只支持中文！");
            return false;
        }
        if (!RegexUtil.checkDigitz(patientAge)) {
            toast = ToastUtil.toastHint(toast,PatientPersonInfoActivity.this,"请输入正确的年龄！");
            return false;
        }
        if (!patientSex.equals("0") && !patientSex.equals("1")) {
            toast = ToastUtil.toastHint(toast,PatientPersonInfoActivity.this,"请选择性别！");
            return false;
        }
        if (patientAddress.equals("")) {
            toast = ToastUtil.toastHint(toast,PatientPersonInfoActivity.this,"请输入地址！");
            return false;
        }
        return true;
    }


    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}